package com.wyx.SpringSecurityConfig;

import com.wyx.utils.TokenManager;
import lombok.extern.java.Log;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

//退出处理器
@Log
public class TokenLogoutHandler implements LogoutHandler {


    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

        // 功能较为简单，只要请求头包含token就能退出，后期根据自己的业务需求更改

        String token = request.getHeader("token");
        if(token != null) {

            // 从 token中获取用户名
            HashMap tokenMap = TokenManager.jwtDecrypt(token);
            try {
                response.sendRedirect("/authority/logoutOk");
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("用户退出登录成功");

            // 在 redis 上删除token,可以删除，也可以不删。
//            redisTemplate.delete(tokenMap.get("username"));
        }else {
            try {
                request.getRequestDispatcher("/authority/logoutEr").forward(request,response);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }
    }
}
